package com.demo.zhlg.util;


import com.demo.zhlg.entity.Users;
import com.demo.zhlg.mapper.UsersMapper;
import com.demo.zhlg.service.impl.LoginUser;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    HandlerExceptionResolver handlerExceptionResolver;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        try{
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                filterChain.doFilter(request, response);
                return;
            }
            Integer userId = (Integer) JwtUtil.parseToken(token, "id");
            Users user = usersMapper.selectOneById(userId);
            if( user == null ){
                filterChain.doFilter(request, response);
                return;
            }
            LoginUser loginUser = new LoginUser(user);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request, response );
        }
        catch (Exception e){
            handlerExceptionResolver.resolveException(request, response, null, e );
        }
    }
}